#include "StdAfx.h"
#include "dvariabletablemodel.h"
#include "dvariableentity.h"
#include "dentityfactory.h"

DVariableTableModel::DVariableTableModel(QList<DVariableEntity*>& variables, QObject *parent)
	: QAbstractTableModel(parent)
	, m_variables(variables)
{

}

DVariableTableModel::~DVariableTableModel()
{

}

int DVariableTableModel::rowCount(const QModelIndex &parent) const
{
	return m_variables.size();
}

int DVariableTableModel::columnCount(const QModelIndex &parent) const
{	
	return 3;
}

QVariant DVariableTableModel::data(const QModelIndex &index, int role) const
{
	QVariant result;

	if(!index.isValid())
	{

	}
	else if(role == Qt::DisplayRole)
	{
		switch(index.column())
		{
		case 0: result = m_variables[index.row()]->name(); break;
		case 1: result = m_variables[index.row()]->type(); break;
		case 2: 
			{
				switch(m_variables[index.row()]->access())
				{
				case ePublic: result = "Public"; break;
				case eProtected: result = "Protected"; break;
				case ePrivate: result = "Private"; break;
				}
			}
			break;
		}
	}

	return result;
}

QVariant DVariableTableModel::headerData(int section, Qt::Orientation orientation,
                         int role) const
{
	QVariant result;

	if(role == Qt::DisplayRole && orientation == Qt::Horizontal)
	{
		switch(section)
		{
			case 0: result = "Name"; break;
			case 1: result = "Type"; break;
			case 2: result = "Access"; break;
		}
	}

	return result;
}

Qt::ItemFlags DVariableTableModel::flags(const QModelIndex &index) const
{
	if (!index.isValid())
         return Qt::ItemIsEnabled;

     return QAbstractItemModel::flags(index) | Qt::ItemIsEditable;
}

bool DVariableTableModel::setData(const QModelIndex &index, const QVariant &value,
					int role)
{
	if (index.isValid() && role == Qt::EditRole) 
	{
         switch(index.column())
		 {
			 // name
			case 0: m_variables[index.row()]->setName(value.toString()); break; 
			case 1: m_variables[index.row()]->setType(value.toString()); break; 
			case 2: 
				{
					if(value.toString() == "Public")
					{
						m_variables[index.row()]->setAccess(ePublic);
					}
					else if(value.toString() == "Protected")
					{
						m_variables[index.row()]->setAccess(eProtected);
					}
					else if(value.toString() == "Private")
					{
						m_variables[index.row()]->setAccess(ePrivate);
					}
				}
				break;
		 }
         emit dataChanged(index, index);
         return true;
     }
     return false;
}

void DVariableTableModel::addVariable(const QString& name, const QString& type, Access access)
{
	beginInsertRows(QModelIndex(), m_variables.size(), m_variables.size());

	DEntityFactory factory;
	DVariableEntity* pNewVar = factory.createVariableEntity(name, type, access);
	m_variables.append(pNewVar);

	endInsertRows();
}